import { useDocumentStore } from '@/common/store';
import { Auxiliaries, KeySet } from '@/common/types';
import { FieldProps } from '@rjsf/utils';
import { Flex, Select } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { get } from 'lodash';

/**
 * 集合选择器，
 */
export function SetField<T = number[]>({
  schema,
  idSchema,
  uiSchema,
  formData,
  disabled,
  onChange,
  formContext, // 获取 form 数据
}: FieldProps<T>) {
  const layout2 = uiSchema['ui:layout'] ?? [1, 1];
  const label = uiSchema?.['ui:options']?.label ?? true;
  const [options, setOptions] = useState(null);
  const { databaseInfo } = useDocumentStore();
  const schemaFormat = useRef<string>(null); // 记录format，用来判断是否发生改变，然后清空数据

  useEffect(() => {
    if (
      schemaFormat.current != null &&
      schemaFormat.current !== schema.format
    ) {
      setTimeout(() => {
        onChange([] as T);
      });
    }
    schemaFormat.current = schema.format;
  }, [schema.format]);

  // 从database获取集合列表，并用列表显示出来让用户选择
  const auxiliaries = databaseInfo?.find((value) => value.name === Auxiliaries);
  const set = auxiliaries?.children
    .find((value) => value.type === KeySet)
    ?.details?.filter((detail) => detail.type === schema.format);

  return (
    <Flex
      style={{ gap: 4 }}
      className='items-center'>
      <Flex
        style={{ flex: layout2[0], gap: 10 }}
        className='items-center'>
        <span
          style={{ flex: 1 }}
          className='fs'>
          {label ? schema.title : ''}
        </span>
      </Flex>
      <Flex
        style={{
          width: 0,
          flex: layout2[1],
          gap: 5,
          overflow: 'hidden',
          fontSize: 12,
        }}>
        <Select
          mode={schema.maxItems <= 1 ? undefined : 'multiple'}
          style={{ width: '100%' }}
          styles={{ popup: { root: { borderRadius: '4px' } } }}
          placeholder='请选择'
          value={formData ?? []}
          onFocus={() => {
            // 在这里动态刷新 options，例如过滤掉 masterRegion 已选值
            const dependPath = uiSchema?.['ui:options']?.dependOn;
            const masterValue = get(formContext?.formData, dependPath);
            const optionsList = (set ?? []).filter(
              (item) => item.id !== masterValue,
            );
            setOptions(optionsList);
          }}
          allowClear
          disabled={disabled ? disabled : uiSchema['ui:disabled']}
          onChange={(value) => onChange(value as T, undefined, idSchema.$id)}>
          {options?.map((item, index) => (
            <Select.Option
              key={index}
              style={{ borderRadius: 'var(--item-border-radius) !important' }}
              disabled={item.disabled}
              value={item.id}
              label={item.name}>
              {item.name}
            </Select.Option>
          ))}
        </Select>
      </Flex>
    </Flex>
  );
}
